package com.sj.uabrowser.mvp.menu.service;

import android.content.Context;
import android.content.Intent;

import com.orhanobut.logger.Logger;
import com.sj.uabrowser.app.TApp;
import com.sj.uabrowser.db.ThreadInfo;
import com.sj.uabrowser.db.gen.FileInfoDao;
import com.sj.uabrowser.db.gen.ThreadInfoDao;
import com.sj.uabrowser.db.FileInfo;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class DownloadTask {

    private Context mConext;
    private FileInfo mFileInfo;
    private ThreadInfoDao mDao;
    private FileInfoDao mFileInfoDao;
//    private ThreadDAO mDao;
    private long mFinished;
    public boolean isPaused;

    public DownloadTask(Context mConext, FileInfo mFileInfo) {
        this.mConext = mConext;
        this.mFileInfo = mFileInfo;
//        mDao = new ThreadDAOImpl(mConext);
        mDao = TApp.getDaoSession().getThreadInfoDao();
        mFileInfoDao = TApp.getDaoSession().getFileInfoDao();
    }

    public void download(){
        //1.读取数据库中的线程信息
        List<ThreadInfo> threadInfos = mDao.queryRaw("where url = ? and filename = ?",new String[]{mFileInfo.getUrl(),mFileInfo.getFileName()});
        ThreadInfo threadInfo = null;
        if(threadInfos.size()==0){
            //2.初始化线程信息对象
            threadInfo = new ThreadInfo(null,mFileInfo.getUrl(),mFileInfo.getFileName(),0,mFileInfo.getLength(),0);
        }else{
            threadInfo = threadInfos.get(0);
        }
        //3.创建子线程进行下载
        new DownloadThread(threadInfo).start();
    }

    private boolean isExistsThread(String url,String filename,Long id){
        List<ThreadInfo> threadInfos = mDao.queryRaw("where url = ? and filename = ? and _id = ?",new String[]{url,filename,id+""});
        return threadInfos.size()>0?true:false;
    }

    class DownloadThread extends Thread {

        private ThreadInfo mThreadInfo = null;

        public DownloadThread(ThreadInfo mThreadInfo) {
            this.mThreadInfo = mThreadInfo;
        }

        @Override
        public void run() {
            //1. 向数据库插入线程信息
            if (!isExistsThread(mThreadInfo.getUrl(),mThreadInfo.getFilename(), mThreadInfo.getId())) {
                mDao.insert(mThreadInfo);
            }
            HttpURLConnection conn = null;
            RandomAccessFile raf = null;
            InputStream inputStream = null;
            try {
                URL url = new URL(mThreadInfo.getUrl());
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(3000);
                conn.setRequestMethod("GET");
                //2. 设置下载位置
                long start = mThreadInfo.getStart() + mThreadInfo.getFinished();
                conn.setRequestProperty("Range", "bytes=" + start + "-" + mThreadInfo.getEnd());

                //3. 设置文件写入位置
                File file = new File(DownloadService.DOWNLOAD_PATH, mFileInfo.getFileName());
                raf = new RandomAccessFile(file, "rwd");
                raf.seek(start);
                //4. 开始下载
                //读取数据
                Intent intent = new Intent(DownloadService.ACTION_UPDATE);
                mFinished += mThreadInfo.getFinished();
                if (conn.getResponseCode() == HttpURLConnection.HTTP_PARTIAL) {
                    inputStream = conn.getInputStream();
                    byte[] buffer = new byte[1024 * 4];
                    int len = -1;
                    long time = System.currentTimeMillis();
                    while ((len = inputStream.read(buffer)) != -1) {
                        //写入文件
                        raf.write(buffer, 0, len);
                        mFinished += len;
                        mFileInfo.setFinished(mFinished);
                        //把下载进度发送广播给activity
                        if (System.currentTimeMillis() - time >= 1000||mFinished==mFileInfo.getLength()) {
                            time = System.currentTimeMillis();
                            intent.putExtra("finished", mFinished);
                            intent.putExtra("filename",mFileInfo.getFileName());
                            intent.putExtra("url",mFileInfo.getUrl());
                            mConext.sendBroadcast(intent);
                        }
                        //在下载暂停时保存下载进度
                        if (isPaused) {
                            List<ThreadInfo> list = mDao.queryRaw("where url = ? and _id= ?",new String[]{mFileInfo.getUrl(), mThreadInfo.getId()+""});
                            if(list.size()>0) {
                                ThreadInfo bean = list.get(0);
                                bean.setFinished(mFinished);
                                mDao.update(bean);

                            }
                            return;
                        }
                    }
                    List<ThreadInfo> list = mDao.queryRaw("where url = ? and filename = ? and _id= ?",new String[]{mFileInfo.getUrl(),mFileInfo.getFileName(), mThreadInfo.getId()+""});
                    int threadSize = list.size();
                    if(threadSize >0){
                        mFileInfoDao.update(mFileInfo);
                        mDao.delete(list.get(0));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    conn.disconnect();
                    if(raf!=null)raf.close();
                    if(inputStream!=null)inputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        }
    }


}
